using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Infrastructure.Configuration.Models;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Notification;
using System;
using System.ComponentModel.DataAnnotations;

namespace JGSY.CMS.LowCode.Platform.Infrastructure.Configuration;

/// <summary>
/// 配置映射工厂 - 增强版
/// 提供完整的 appsettings.json 配置映射功能
/// </summary>
public class ConfigurationMappingFactory
{
    private readonly AppSettingsMapper _mapper;
    private readonly ILogger<ConfigurationMappingFactory>? _logger;

    public ConfigurationMappingFactory(IConfiguration configuration, ILogger<ConfigurationMappingFactory>? logger = null)
    {
        _mapper = new AppSettingsMapper(configuration);
        _logger = logger;
    }

    #region 核心配置获取方法

    /// <summary>
    /// 获取数据库配置
    /// </summary>
    /// <returns>数据库配置</returns>
    public DatabaseConfiguration GetDatabaseConfiguration()
    {
        var config = _mapper.BindRoot<DatabaseConfiguration>();
        
        // 额外的验证逻辑
        ValidateDatabaseConfiguration(config);
        _logger?.LogDebug("Database configuration loaded: {DatabaseType}", config.DatabaseType);
        
        return config;
    }

    /// <summary>
    /// 获取日志配置
    /// </summary>
    /// <returns>日志配置</returns>
    public LoggingConfiguration GetLoggingConfiguration()
    {
        var config = _mapper.Bind<LoggingConfiguration>("Logging");
        _logger?.LogDebug("Logging configuration loaded with default level: {DefaultLevel}", config.LogLevel?.Default ?? "Information");
        return config;
    }

    /// <summary>
    /// 获取Serilog自定义配置
    /// </summary>
    /// <returns>Serilog配置</returns>
    public SerilogCustConfiguration GetSerilogCustConfiguration()
    {
        var config = _mapper.Bind<SerilogCustConfiguration>("SerilogCust");
        _logger?.LogDebug("SerilogCust configuration loaded: ForceToEnable={ForceToEnable}", config.ForceToEnable);
        return config;
    }

    /// <summary>
    /// 获取Serilog完整配置
    /// </summary>
    /// <returns>Serilog配置</returns>
    public SerilogConfiguration GetSerilogConfiguration()
    {
        var config = _mapper.Bind<SerilogConfiguration>("Serilog");
        _logger?.LogDebug("Serilog configuration loaded with {WritersCount} writers", config.WriteTo?.Count ?? 0);
        return config;
    }

    /// <summary>
    /// 获取JWT配置
    /// </summary>
    /// <returns>JWT配置</returns>
    public JwtConfiguration GetJwtConfiguration()
    {
        var config = _mapper.Bind<JwtConfiguration>("Jwt");
        ValidateJwtConfiguration(config);
        _logger?.LogDebug("JWT configuration loaded: HasSecret={HasSecret}", !string.IsNullOrEmpty(config.Secret));
        return config;
    }

    /// <summary>
    /// 获取服务器配置
    /// </summary>
    /// <returns>服务器配置</returns>
    public ServerConfiguration GetServerConfiguration()
    {
        var config = _mapper.Bind<ServerConfiguration>("Server");
        _logger?.LogDebug("Server configuration loaded: Port={Port}, Environment={Environment}", config.Port, config.Environment);
        return config;
    }

    /// <summary>
    /// 获取缓存设置配置
    /// </summary>
    /// <returns>缓存设置配置</returns>
    public CacheSettingsConfiguration GetCacheSettingsConfiguration()
    {
        var config = _mapper.Bind<CacheSettingsConfiguration>("CacheSettings");
        _logger?.LogDebug("Cache configuration loaded: Provider={Provider}", config.Provider);
        return config;
    }

    #endregion

    #region 扩展配置获取方法

    /// <summary>
    /// 获取允许的主机配置
    /// </summary>
    /// <returns>允许的主机配置</returns>
    public AllowedHostsConfiguration GetAllowedHostsConfiguration()
    {
        var hosts = _mapper.GetValue<string>("AllowedHosts", "*");
        return new AllowedHostsConfiguration { Hosts = hosts };
    }

    /// <summary>
    /// 获取安全配置
    /// </summary>
    /// <returns>安全配置</returns>
    public SecurityConfiguration GetSecurityConfiguration()
    {
        var config = _mapper.Bind<SecurityConfiguration>("CacheSettings:Security");
        ValidateSecurityConfiguration(config);
        _logger?.LogDebug("Security configuration loaded: EnableMFA={EnableMFA}, EnableThreatDetection={EnableThreatDetection}", 
            config.EnableMFA, config.EnableThreatDetection);
        return config;
    }

    /// <summary>
    /// 获取上传配置
    /// </summary>
    /// <returns>上传配置</returns>
    public UploadConfiguration GetUploadConfiguration()
    {
        var config = _mapper.Bind<UploadConfiguration>("CacheSettings:Upload");
        ValidateUploadConfiguration(config);
        _logger?.LogDebug("Upload configuration loaded: StorageType={StorageType}, MaxFileSize={MaxFileSize}", 
            config.StorageType, config.MaxFileSize);
        return config;
    }

    /// <summary>
    /// 获取SMS配置 - 已重定向到新的企业级SMS服务
    /// </summary>
    /// <returns>SMS服务配置</returns>
    public SmsServiceOptions GetSmsConfiguration()
    {
        var config = _mapper.Bind<SmsServiceOptions>("SmsService");
        _logger?.LogDebug("SMS service configuration loaded: Provider={Provider}, EnableFailover={EnableFailover}", 
            config.DefaultProvider, config.EnableFailover);
        return config;
    }

    /// <summary>
    /// 获取CORS配置
    /// </summary>
    /// <returns>CORS配置</returns>
    public CorsConfiguration GetCorsConfiguration()
    {
        var config = _mapper.Bind<CorsConfiguration>("CacheSettings:Cors");
        _logger?.LogDebug("CORS configuration loaded: Origin={Origin}", config.Origin);
        return config;
    }

    /// <summary>
    /// 获取API配置
    /// </summary>
    /// <returns>API配置</returns>
    public ApiConfiguration GetApiConfiguration()
    {
        var config = _mapper.Bind<ApiConfiguration>("CacheSettings:Api");
        _logger?.LogDebug("API configuration loaded: Prefix={Prefix}", config.Prefix);
        return config;
    }

    /// <summary>
    /// 获取速率限制配置
    /// </summary>
    /// <returns>速率限制配置</returns>
    public RateLimitConfiguration GetRateLimitConfiguration()
    {
        var config = _mapper.Bind<RateLimitConfiguration>("CacheSettings:RateLimit");
        _logger?.LogDebug("RateLimit configuration loaded: Enabled={Enabled}", config.Enabled);
        return config;
    }

    /// <summary>
    /// 获取锁定配置
    /// </summary>
    /// <returns>锁定配置</returns>
    public LockConfiguration GetLockConfiguration()
    {
        var config = _mapper.Bind<LockConfiguration>("CacheSettings:Locked");
        _logger?.LogDebug("Lock configuration loaded: Enabled={Enabled}", config.Enabled);
        return config;
    }

    /// <summary>
    /// 获取权限配置
    /// </summary>
    /// <returns>权限配置</returns>
    public PermissionConfiguration GetPermissionConfiguration()
    {
        var config = _mapper.Bind<PermissionConfiguration>("CacheSettings:Permission");
        _logger?.LogDebug("Permission configuration loaded: Enabled={Enabled}", config.Enabled);
        return config;
    }

    /// <summary>
    /// 获取扩展配置
    /// </summary>
    /// <returns>扩展配置</returns>
    public ExtensionConfiguration GetExtensionConfiguration()
    {
        var config = _mapper.Bind<ExtensionConfiguration>("CacheSettings:Extension");
        _logger?.LogDebug("Extension configuration loaded: EnableDatabaseExtensions={EnableDatabaseExtensions}", config.EnableDatabaseExtensions);
        return config;
    }

    /// <summary>
    /// 获取MongoDB配置
    /// </summary>
    /// <returns>MongoDB配置</returns>
    public MongoDbConfiguration GetMongoDbConfiguration()
    {
        var config = _mapper.Bind<MongoDbConfiguration>("CacheSettings:MongoDb");
        _logger?.LogDebug("MongoDB configuration loaded: Url={Url}", config.Url);
        return config;
    }

    /// <summary>
    /// 获取ClickHouse配置
    /// </summary>
    /// <returns>ClickHouse配置</returns>
    public ClickHouseConfiguration GetClickHouseConfiguration()
    {
        var config = _mapper.Bind<ClickHouseConfiguration>("CacheSettings:ClickHouse");
        _logger?.LogDebug("ClickHouse configuration loaded: Url={Url}, Database={Database}", config.Url, config.Database);
        return config;
    }

    #endregion

    /// <summary>
    /// 获取所有配置的汇总 - 增强版
    /// </summary>
    /// <returns>完整的应用配置</returns>
    public EnhancedAppSettingsConfiguration GetCompleteConfiguration()
    {
        _logger?.LogInformation("Loading complete application configuration...");
        
        try
        {
            var config = new EnhancedAppSettingsConfiguration
            {
                Database = GetDatabaseConfiguration(),
                Logging = GetLoggingConfiguration(),
                SerilogCust = GetSerilogCustConfiguration(),
                Serilog = GetSerilogConfiguration(),
                Jwt = GetJwtConfiguration(),
                Server = GetServerConfiguration(),
                CacheSettings = GetCacheSettingsConfiguration(),
                AllowedHosts = GetAllowedHostsConfiguration(),
                Security = GetSecurityConfiguration(),
                Upload = GetUploadConfiguration(),
                Sms = GetSmsConfiguration(),
                Cors = GetCorsConfiguration(),
                Api = GetApiConfiguration(),
                RateLimit = GetRateLimitConfiguration(),
                Lock = GetLockConfiguration(),
                Permission = GetPermissionConfiguration(),
                Extension = GetExtensionConfiguration(),
                MongoDb = GetMongoDbConfiguration(),
                ClickHouse = GetClickHouseConfiguration(),
                LoadedAt = DateTime.UtcNow
            };

            _logger?.LogInformation("Complete application configuration loaded successfully at {LoadedAt}", config.LoadedAt);
            return config;
        }
        catch (Exception ex)
        {
            _logger?.LogError(ex, "Failed to load complete application configuration");
            throw;
        }
    }

    #region 配置验证方法

    /// <summary>
    /// 验证数据库配置
    /// </summary>
    /// <param name="config">数据库配置</param>
    private void ValidateDatabaseConfiguration(DatabaseConfiguration config)
    {
        var connectionString = config.ConnectionStrings.GetConnectionString(config.DatabaseType);
        
        if (string.IsNullOrEmpty(connectionString))
        {
            var errorMessage = $"Connection string for database type '{config.DatabaseType}' is not configured.";
            _logger?.LogError(errorMessage);
            throw new InvalidOperationException(errorMessage);
        }

        _logger?.LogDebug("Database configuration validation passed for type: {DatabaseType}", config.DatabaseType);
    }

    /// <summary>
    /// 验证JWT配置
    /// </summary>
    /// <param name="config">JWT配置</param>
    private void ValidateJwtConfiguration(JwtConfiguration config)
    {
        if (string.IsNullOrEmpty(config.Secret))
        {
            var errorMessage = "JWT Secret is required but not configured.";
            _logger?.LogError(errorMessage);
            throw new InvalidOperationException(errorMessage);
        }

        if (config.Secret.Length < 32)
        {
            var errorMessage = "JWT Secret must be at least 32 characters long for security.";
            _logger?.LogWarning(errorMessage);
        }

        _logger?.LogDebug("JWT configuration validation passed");
    }

    /// <summary>
    /// 验证安全配置
    /// </summary>
    /// <param name="config">安全配置</param>
    private void ValidateSecurityConfiguration(SecurityConfiguration config)
    {
        if (config.MaxLoginAttempts <= 0)
        {
            _logger?.LogWarning("MaxLoginAttempts should be greater than 0, current value: {MaxLoginAttempts}", config.MaxLoginAttempts);
        }

        if (config.LockoutDuration < 60)
        {
            _logger?.LogWarning("LockoutDuration should be at least 60 seconds for security, current value: {LockoutDuration}", config.LockoutDuration);
        }

        _logger?.LogDebug("Security configuration validation passed");
    }

    /// <summary>
    /// 验证上传配置
    /// </summary>
    /// <param name="config">上传配置</param>
    private void ValidateUploadConfiguration(UploadConfiguration config)
    {
        if (config.MaxFileSize <= 0)
        {
            var errorMessage = "MaxFileSize must be greater than 0.";
            _logger?.LogError(errorMessage);
            throw new InvalidOperationException(errorMessage);
        }

        if (config.AllowedExtensions == null || config.AllowedExtensions.Count == 0)
        {
            _logger?.LogWarning("No allowed file extensions configured, this may pose security risks");
        }

        _logger?.LogDebug("Upload configuration validation passed");
    }

    #endregion

    /// <summary>
    /// 获取配置健康状态
    /// </summary>
    /// <returns>配置健康状态</returns>
    public ConfigurationHealthStatus GetHealthStatus()
    {
        var health = new ConfigurationHealthStatus
        {
            IsHealthy = true,
            CheckedAt = DateTime.UtcNow,
            Issues = new List<string>()
        };

        try
        {
            // 验证关键配置
            GetDatabaseConfiguration();
            GetJwtConfiguration();
            
            _logger?.LogDebug("Configuration health check passed");
        }
        catch (Exception ex)
        {
            health.IsHealthy = false;
            health.Issues.Add($"Configuration validation failed: {ex.Message}");
            _logger?.LogError(ex, "Configuration health check failed");
        }

        return health;
    }

    /// <summary>
    /// 清除所有缓存
    /// </summary>
    public void ClearCache()
    {
        _mapper.ClearCache();
        _logger?.LogDebug("Configuration cache cleared");
    }
}

/// <summary>
/// 完整的应用设置配置 - 基础版
/// </summary>
public class AppSettingsConfiguration
{
    public DatabaseConfiguration Database { get; set; } = new();
    public LoggingConfiguration Logging { get; set; } = new();
    public SerilogCustConfiguration SerilogCust { get; set; } = new();
    public SerilogConfiguration Serilog { get; set; } = new();
    public JwtConfiguration Jwt { get; set; } = new();
    public ServerConfiguration Server { get; set; } = new();
    public CacheSettingsConfiguration CacheSettings { get; set; } = new();
    public AllowedHostsConfiguration AllowedHosts { get; set; } = new();
}

/// <summary>
/// 增强版应用设置配置 - 包含完整的 appsettings.json 映射
/// </summary>
public class EnhancedAppSettingsConfiguration : AppSettingsConfiguration
{
    /// <summary>
    /// 安全配置
    /// </summary>
    public SecurityConfiguration Security { get; set; } = new();

    /// <summary>
    /// 上传配置
    /// </summary>
    public UploadConfiguration Upload { get; set; } = new();

    /// <summary>
    /// SMS 配置 - 企业级短信服务配置
    /// </summary>
    public SmsServiceOptions Sms { get; set; } = new();

    /// <summary>
    /// CORS 配置
    /// </summary>
    public CorsConfiguration Cors { get; set; } = new();

    /// <summary>
    /// API 配置
    /// </summary>
    public ApiConfiguration Api { get; set; } = new();

    /// <summary>
    /// 速率限制配置
    /// </summary>
    public RateLimitConfiguration RateLimit { get; set; } = new();

    /// <summary>
    /// 锁定配置
    /// </summary>
    public LockConfiguration Lock { get; set; } = new();

    /// <summary>
    /// 权限配置
    /// </summary>
    public PermissionConfiguration Permission { get; set; } = new();

    /// <summary>
    /// 扩展配置
    /// </summary>
    public ExtensionConfiguration Extension { get; set; } = new();

    /// <summary>
    /// MongoDB 配置
    /// </summary>
    public MongoDbConfiguration MongoDb { get; set; } = new();

    /// <summary>
    /// ClickHouse 配置
    /// </summary>
    public ClickHouseConfiguration ClickHouse { get; set; } = new();

    /// <summary>
    /// 配置加载时间
    /// </summary>
    public DateTime LoadedAt { get; set; } = DateTime.UtcNow;

    /// <summary>
    /// 配置版本
    /// </summary>
    public string Version { get; set; } = "1.0.0";

    /// <summary>
    /// 环境名称
    /// </summary>
    public string Environment { get; set; } = "Development";
}

/// <summary>
/// 配置健康状态
/// </summary>
public class ConfigurationHealthStatus
{
    /// <summary>
    /// 配置是否健康
    /// </summary>
    public bool IsHealthy { get; set; }

    /// <summary>
    /// 检查时间
    /// </summary>
    public DateTime CheckedAt { get; set; }

    /// <summary>
    /// 问题列表
    /// </summary>
    public List<string> Issues { get; set; } = new();

    /// <summary>
    /// 警告列表
    /// </summary>
    public List<string> Warnings { get; set; } = new();
}
